
<template>
  <a-card>
    <!-- 单据 -->
    <a-form-model ref="ruleForm" :model="Form" v-bind="layout" :rules="rules"
      ><!-- 顶部的信息  -->
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号" prop="document" ref="document">
            <a-input
              style="border: 0"
              v-model="Form.document"
              disabled
            ></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="单据日期"
            prop="document_date"
            ref="document_date"
          >
            <a-date-picker
              v-model="Form.document_date"
              type="date"
              placeholder="请选择时间"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="组装费用">
            <a-input-number
              style="width: 100%"
              :step="0.001"
              v-model="Form.assemblyTotalCost"
            >
            </a-input-number>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="供应商" prop="supplier" ref="supplier">
            <a-select
              v-model="Form.supplier"
              @change="getSupplierId"
              style="width: 100%"
              showSearch
              @search="getConstructionUnitList"
            >
              <a-select-option
                v-for="item in SupplierList"
                :key="item.id"
                :value="item.suppilerName"
              >
                {{ item.suppilerName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="公司" ref="corp" prop="corp">
            <a-tree-select
              v-model="Form.corp"
              show-search
              style="width: 100%"
              allow-clear
              :tree-data="CorpList"
              @change="getCorpId"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库存组织" ref="bodyname" prop="bodyname">
            <a-select
              v-model="Form.bodyname"
              @change="getpk_calbodyId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in InventoryOrganizationList"
                :key="item.id"
                :value="item.pkCalbody + '|' + item.bodyname"
              >
                {{ item.bodycode }}
                {{ item.bodyname }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>

      <!-- <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="备注">
            <a-textarea
              v-model="Form.remarks"
              :auto-size="{ minRows: 2, maxRows: 6 }" 
            />
          </a-form-model-item>
        </a-col>
      </a-row> -->

      <!-- 生成原单按钮组件 -->
      <AssemblyCalculationSheet
        @send-data="setGoodsListInfo"
      ></AssemblyCalculationSheet>

      <!-- 单据对应表格 -->
      <a-table
        :columns="columns"
        :data-source="DataSource"
        style="margin-top: 10px"
        :pagination="false"
        :scroll="autoSize"
      >
        <!-- 组装类型 -->
        <span slot="assembleType" slot-scope="text, record">
          <a-select
            v-model="record.assembleType"
            @change="getGoodsInfoByAssembleType(record.key)"
            showSearch
            style="width: 100%"
            disabled
          >
            <a-select-option
              v-for="(item, index) in assembleTypeList"
              :key="index"
              :value="item.value"
            >
              {{ item.title }}
            </a-select-option>
          </a-select>
        </span>
        <!-- 仓库编码 -->
        <span slot="depotNo" slot-scope="text, record">
          <a-select
            v-model="record.depotNo"
            @change="getDepotId(record.key)"
            showSearch
            style="width: 100%"
          >
            <a-select-option
              v-for="item in storageList"
              :key="item.depotNo"
              :value="item.depotNo + '|' + item.depotName"
            >
              {{ item.depotNo }} {{ item.depotName }}
            </a-select-option>
          </a-select>
        </span>
        <!-- 库位 -->
        <!-- <span slot="depotLocation" slot-scope="text, record">
        <a-tree-select
          v-model="record.depotLocation"
          style="width: 100%"
          :tree-data="record.positionList"
          allow-clear
        ></a-tree-select>
      </span> -->
        <!-- 仓位 -->
        <span slot="position" slot-scope="text, record">
          <a-tree-select
            v-model="record.position"
            style="width: 100%"
            :tree-data="record.positionList"
            allow-clear
          ></a-tree-select>
        </span>

        <!-- 存货编码 -->
        <span slot="inventoryNo" slot-scope="text, record">
          <!-- 這是配件 -->
          <a-select
            v-if="record.assembleType == 1"
            v-model="record.inventoryNo"
            style="width: 100%"
            @change="getInventoryInfo(record.key)"
            showSearch
          >
            <a-select-option
              v-for="item in record.packageInventoryInformationList"
              :key="item.inventoryId"
              :value="item.inventoryNo + '|' + item.inventoryName"
            >
              {{ item.inventoryNo }} {{ item.inventoryName }}
            </a-select-option>
          </a-select>
          <!-- 這是成套件 -->
          <a-select
            v-if="record.assembleType != 1"
            v-model="record.inventoryNo"
            style="width: 100%"
            @change="getInventoryInfo(record.key)"
            showSearch
          >
            <a-select-option
              v-for="item in record.partsInventoryInformationList"
              :key="item.inventoryId"
              :value="item.inventoryNo + '|' + item.inventoryName"
            >
              {{ item.inventoryNo }} {{ item.inventoryName }}
            </a-select-option>
          </a-select>
        </span>

        <!-- 辅助单位 -->
        <span slot="auxiliaryUnit" slot-scope="text, record">
          <a-select
            v-model="record.auxiliaryUnit"
            style="width: 100%"
            showSearch
          >
            <a-select-option
              v-for="item in Auxiliary_Unitlist"
              :key="item.value"
              :value="item.title + '|' + item.value"
            >
              {{ item.value }} {{ item.title }}
            </a-select-option>
          </a-select>
        </span>

        <!-- 数量 -->
        <span slot="number" slot-scope="text, record">
          <a-input-number v-model="record.number" :min="0" :precision="3" />
        </span>

        <!-- 收发类别 -->
        <span slot="sendReceiveType" slot-scope="text, record">
          <a-select
            v-model="record.sendReceiveType"
            @change="getSendReceiveId(record.key)"
            style="width: 100%"
          >
            <a-select-option
              v-for="(item, index) in SendReceiveList"
              :key="index"
              :value="item.id + '|' + item.name"
              >{{ item.name }}
            </a-select-option>
          </a-select>
        </span>

        <!-- 批次号 -->
        <span slot="batchNo" slot-scope="text, record">
          <a-select v-model="record.batchNo" style="width: 100%">
            <a-select-option
              v-for="(item, index) in record.BatchList"
              :key="index"
              :value="item"
            >
              {{ item }}
            </a-select-option>
          </a-select>
        </span>

        <!-- 转库日期 -->
        <span slot="transferDate" slot-scope="text, record">
          <a-date-picker
            v-model="record.transferDate"
            type="date"
            @change="getTransferDate(record.key)"
            placeholder="请选择时间"
            style="width: 100%"
          />
        </span>

        <!-- 备注 -->
        <span slot="remark" slot-scope="text, record">
          <a-input v-model="record.remark"> </a-input>
        </span>

        <template slot="action" slot-scope="text, record">
          <span v-if="record.isNew">
            <a @click="cancle(record.key)">取消</a>
          </span>
          <span v-else>
            <a-popconfirm
              ok-text="确定"
              cancel-text="取消"
              @confirm="Delete(record.id)"
            >
              <template slot="title">
                <p>确定删除？</p>
              </template>
              <a type="danger"> 删除 </a>
            </a-popconfirm>
          </span>
        </template>
      </a-table>

      <!-- <a-button
      style="width: 100%; margin-top: 16px; margin-bottom: 8px"
      type="dashed"
      icon="plus"
      @click="newMember"
      >添加</a-button
    > -->

      <div style="margin-top: 20px">
        <!-- 单据 -->

        <a-row>
          <!-- <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item
              label="负责人"
              ref="responsiblePerson"
              prop="responsiblePerson"
            >
              <a-select
                v-model="Form.responsiblePerson"
                style="width: 100%"
                showSearch
                @change="setResponsible_person"
              >
                <a-select-option
                  v-for="item in responsiblePersonList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col> -->

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核人" ref="inspector" prop="inspector">
              <a-select
                v-model="Form.inspector"
                showSearch
                @change="setInspector"
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in inspectorList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期" ref="" prop="">
              <a-date-picker
                v-model="Form.balance"
                type="date"
                style="width: 100%"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="制单人" ref="" prop="">
              <a-input disabled v-model="Form.singleProducer"> </a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <!-- 提交按钮组  -->
        <div style="margin-top: 20px">
          <center>
            <!-- <a-button type="primary" style="margin-right: 20px"> 打印 </a-button> -->
            <a-button @click="Save" style="margin-right: 20px"> 保存 </a-button>
            <a-button style="margin-right: 20px" disabled> 审核 </a-button>
            <!-- <a-button type="primary" style="margin-right: 20px" disabled>
            提交
          </a-button> -->
          </center>
        </div>
      </div>
    </a-form-model>
  </a-card>
</template>

<script>
// 组装计算表
import AssemblyCalculationSheet from "../../components/common/AssemblyCalculationSheet";

import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
// 1. 导入

import { BeiHuoTongZhiHttp } from "@/services/modules/ChuKuGuanLi/XiaoShouChuKu/BeiHuoTongZhi";
const bhtzjHttp = new BeiHuoTongZhiHttp(); // 备货通知

import moment from "moment";
import { mapState, mapGetters } from "vuex";

let columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    width: "80px",
  },
  {
    title: "组装类型",
    key: "assembleType",
    dataIndex: "assembleType",
    align: "center",
    scopedSlots: { customRender: "assembleType" },
  },
  {
    title: "仓库编码",
    key: "depotNo",
    dataIndex: "depotNo",
    align: "center",
    // scopedSlots: { customRender: "depotNo" },
  },
  {
    title: "仓库名称",
    key: "depotName",
    dataIndex: "depotName",
    align: "center",
  },

  // {
  //   title: "库位",
  //   key: "depotLocation",
  //   dataIndex: "depotLocation",
  //   align: "center",
  //   scopedSlots: { customRender: "depotLocation" },
  // },

  {
    title: "仓位",
    key: "position",
    dataIndex: "position",
    align: "center",
    scopedSlots: { customRender: "position" },
  },
  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",
    align: "center",
    // scopedSlots: { customRender: "inventoryNo" },
  },
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "standardModel",
    key: "standardModel",
    align: "center",
  },
  {
    title: "单位",
    key: "unit",
    dataIndex: "unit",
    align: "center",
  },
  {
    title: "数量",
    key: "number",
    dataIndex: "number",
    align: "center",
    // scopedSlots: { customRender: "number" },
  },
  {
    title: "金额",
    key: "money",
    dataIndex: "money",
    align: "center",
  },
  {
    title: "收发类别",
    key: "sendReceiveType",
    dataIndex: "sendReceiveType",
    align: "center",
    scopedSlots: { customRender: "sendReceiveType" },
  },

  {
    title: "批次号",
    key: "batchNo",
    dataIndex: "batchNo",
    align: "center",
    scopedSlots: { customRender: "batchNo" },
  },
  {
    title: "转库日期",
    key: "transferDate",
    dataIndex: "transferDate",
    align: "center",
    scopedSlots: { customRender: "transferDate" },
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
  // {
  //   title: "操作",
  //   dataIndex: "action",
  //   key: "action",
  //   align: "center",
  //   fixed: "right",
  //   scopedSlots: { customRender: "action" },
  // },
];

export default {
  // 2. 注册
  components: {
    AssemblyCalculationSheet,
  },
  computed: {
    // 获取本地数据
    ...mapState("user", { currUser: "info", currPost: "position" }),
    ...mapGetters({
      getDepsInfo: "user/getDepsInfo",
    }),
    // ...mapState("setting", ["isMobile"]),
  },
  data() {
    return {
      rules: {
        document_date: [
          { required: true, message: "请输入单据日期", trigger: "change" },
        ],
        supplier: [
          {
            required: true,
            message: "请输入供应商",
            trigger: "change",
          },
        ],
        corp: [{ required: true, message: "请输入公司", trigger: "change" }],
        bodyname: [
          {
            required: true,
            message: "请输入库存组织",
            trigger: "change",
          },
        ],
        inspector: [
          {
            required: true,
            message: "请输入审核人",
            trigger: "change",
          },
        ],
      },

      // ----- 申请的表单内容信息 -----
      Form: {
        document: "", // 单据号
        document_date: moment().format("YYYY-MM-DD"), // 单据日期
        assemblyTotalCost: 0, // 组装费用
        supplier: "", // 供应商 -- 挂账单位
        supplierId: "", // 供应商Id

        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: null, // 审核日期
        singleProducer: this.$store.state.user.info.username, // 制单人
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
        remarks: "", // 备注

        pkCalbody: "", //!库存组织名称id
        bodyname: "", //库存组织名称

        corp: "1000|山东七河生物科技股份有限公司", // 公司名称
        corpId: "1000", // 公司Id
      },

      // 字典表等数据
      assembleTypeList: [], // 组装类型列表
      storageList: [], // 仓库列表
      // 库位列表
      positionList: [], // 仓位列表
      SendReceiveList: [], // 收发类别列表
      batchNumberList: [], // 批次号列表
      SupplierList: [], // 供应商列表
      CorpList: [], //公司列表
      responsiblePersonList: [], // 负责人列表
      inspectorList: [], // 审核人列表
      InventoryOrganizationList: [], // 库存组织列表
      Auxiliary_Unitlist: [], // 辅助单位列表
      inspectorIdList: [], // 审核人Id列表
      UpdateTmp: false, // 修改标志

      packageInventoryInformationList: [], // 列表
      partsInventoryInformationList: [], // 套件列表

      // 配件列表
      // 成套件列表

      // 格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      // ------- 表格 --------

      // 列表
      columns,
      DataSource: [],
      selectedRowKeys: [],

      autoSize: {
        x: 3500,
        y: 670,
      },

      ExamineDisplay: true, // 审核、提交按钮是否显示

      empty_: true,
    };
  },

  watch: {
    $route: function (to, form) {
      if (to.path == "/Assemble" && form.path == "/AssembleList") {
        console.log("--------- 更新视图 组装  ----------");

        if (this.$route.query.Id) {
          this.getRouterParam();
        }
      }
    },
  },

  // 生命周期函数
  mounted() {
    this.judgeDocument();//判断单据号是否为空
    this.setDataSource(); // 生成多条数据
    this.getCorpInfo(); //获取公司
    this.getApplyOrder(); // 获取申请单号
    this.getApplyStorage(); // 获取仓库
    this.getResponsiblePersonList(); // 获取负责人列表
    this.getInspectorList(); // 获取审核人
    this.getSyncInventoryOrganizationList(); //获取库存组织列表
    this.getAssemblyList(); // 组装类型
    this.getSendReceiveList(); // 获取收发类别列表
    this.getRouterParam(); // 获取路由参数
  },
  //监听
  methods: {
       // ————判断单据号是否为空————
    judgeDocument(){
      setTimeout(() =>{
        if (this.Form.document === "") {
        this.$message.error("未获取到单据号,请刷新页面重试");
      }},3000)
    },
    // 供应商
    getConstructionUnitList(value) {
      this.SupplierList = [];
      if (value != "" && value != " ") {
        console.log(value);
        comHttp
          .getSyncregionalClassiFicationListByName(
            "?customerName=" + value + "&custflag=1,3"
          )
          .then((res) => {
            console.log(res);
            // 递归替换value和title
            res.result.list.forEach((element) => {
              let data = {
                id: element.pkCumandoc,
                suppilerName: element.custname,
                suppilerCode: element.custcode,
              };

              this.SupplierList.push(data);
            });
          });
      }
    },
    // 公司
    getCorpInfo() {
      comHttp.getpk_corpList().then((res) => {
        this.CorpList = res.result;
        this.changeCorpData(this.CorpList);

        console.log("所有公司信息::::", this.CorpList);
      });
    },
    getpk_calbodyId(value) {
      console.log("value", value);
      let array = value.split("|");
      this.Form.pkCalbody = array[0];
      console.log("this.Form.pkCalbody", this.Form.pkCalbody);
    },
    getSyncInventoryOrganizationList() {
      comHttp.getSyncInventoryOrganizationList().then((res) => {
        console.log("库存组织", res);
        this.InventoryOrganizationList = res.result;
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.unitcode + " " + element.unitname;
        element["value"] = element.unitcode + "|" + element.unitname;
        element["children"] = element.syncCompanyEntityList;
        element["key"] = element.id;
        if (element.children) {
          this.changeCorpData(element.children);
        }
      });
    },
    // 获取路由参数
    getRouterParam() {
      console.log("查询参数:::", this.$route.query.Id);
      // 通过出入库id 查询出入库信息
      if (typeof this.$route.query.Id == "undefined") {
        console.log("常规跳转");
      } else {
        this.setInitInfo(this.$route.query.Id);
      }
    },

    // 通过路由跳转，设置初始化信息
    async setInitInfo(id) {
      this.DataSource = [];
      bhtzjHttp.getAssemblyOrderAndGoodsList("?id=" + id).then((res) => {
        console.log("通过Id查询出来的信息::::", res);
        this.otherId = res.result.records[0].id; // 表一 Id
        this.Form = {
          id: res.result.records[0].id, // 表一 Id
          document: res.result.records[0].document, // 单据号
          document_date: res.result.records[0].documentTime, // 单据日期
          assemblyTotalCost: res.result.records[0].assemblyCost, // 组装费用
          // 供应商
          supplier: res.result.records[0].farmer_dictText, // 供应商 -- 挂账单位
          supplierId: res.result.records[0].farmer, // 供应商Id
          // responsiblePerson: res.result.records[0]., // 负责人
          inspector: res.result.records[0].reviewer_dictText, // 审核人
          inspectorId: res.result.records[0].reviewer, // 审核人
          singleProducer: res.result.records[0].preparedBy_dictText, // 制单人
          singleProducerId: res.result.records[0].preparedBy, // 制单人

          /* 修改 */
          corp: res.result.records[0].pkCorp_dictText, // 公司
          corpId: res.result.records[0].pkCorp,
          bodyname: res.result.records[0].pkCalbody_dictText, // 库存组织
          pkCalbody: res.result.records[0].pkCalbody,
        };

        for (let i = 0; i < res.result.records.length; i++) {
          let data = {
            key: i + 1,
            id: res.result.records[i].twoId, // 表二Id

            assembleType: res.result.records[i].type, // 组装类型

            // depotNo: res.result.records[i].depotId_dictText, // 仓库编码
            depotName: res.result.records[i].depotId_dictText, // 仓库名称
            depotId: res.result.records[i].depotId, // 仓库Id

            //depotLocation: res.result.records[i].depotLocation, // 库位
            position: res.result.records[i].position, // 仓位

            inventoryId: res.result.records[i].inventoryId, // 存货编码
            inventoryNo: res.result.records[i].invcode, // 存货编码
            inventoryName: res.result.records[i].inventoryId_dictText, // 存货名称
            specificationsModel: res.result.records[i].specificationsModel, // 规格型号
            unit: res.result.records[i].measname, // 单位

            number: res.result.records[i].number, // 数量
            money: res.result.records[i].money, // 金额

            sendReceiveType:
              res.result.records[i].sendAndReceiveCategory_dictText, // 收发类别
            sendReceiveTypeId: res.result.records[i].sendAndReceiveCategory, // 收发类别
            batchNo: res.result.records[i].batchNo, // 批次号

            transferDate: res.result.records[i].transferDate, // 转库日期
            remark: res.result.records[i].remark, // 备注

            packageInventoryInformationList:
              this.getPackageInventoryInformationList(),
            partsInventoryInformationList:
              this.getPartsInventoryInformationList(),
          };

          // 获取批次号列表
          this.getBatchNumberList(
            res.result.records[i].depotId,
            res.result.records[i].inventoryId
          ).then(async (res) => {
            this.$set(data, "BatchList", res);
          });
          // 获取仓位、库位列表
          this.getPositionList(res.result.records[i].depotId).then(
            async (res) => {
              let temp_data = await this.disableParent(res);
              console.log("獲取的數據:::", temp_data);
              this.$set(data, "positionList", temp_data);
            }
          );
          this.DataSource.push(data);
        }
        console.log("表格信息:::::", this.DataSource);
        this.UpdateTmp = false;
      });
    },

    // 默认设置两行，让用户方便添加
    setDataSource() {
      // let size = 2;
      this.DataSource = [];
      // for (let i = 0; i < size; i++) {
      //   let data = {
      //     key: i + 1,
      //     isNew: true,
      //     assembleType: "", //     组装类型
      //     depotName: "", // 仓库名称
      //     depotNo: "", // 仓库编码
      //     depotId: "", // 仓库Id
      //     position: "", // 仓位
      //     //depotLocation: "", // 库位
      //     inventoryId: "", // 存货Id
      //     inventoryNo: "", // 存货编码
      //     inventoryName: "", //  存货名称
      //     standardModel: "", // , 规格型号
      //     unit: "", // 单位
      //     number: "", // 	数量
      //     money: "", // 金额
      //     sendReceiveType: "", // 收发类别
      //     sendReceiveTypeId: "", // 收发类别Id
      //     batchNo: "", // 批次号
      //     transferDate: "", // 转库日期
      //     remark: "", // 备注
      //     packageInventoryInformationList: [], // 配件列表
      //     partsInventoryInformationList: [], // 成套件列表
      //     positionList: [],
      //     BatchList: [], // 批次号列表
      //   };
      //   this.DataSource.push(data);
      // }
    },

    // 表格添加新的一条记录
    newMember() {
      this.DataSource.push({
        key: this.DataSource.length + 1,
        isNew: true,
        assembleType: "", //     组装类型
        depotName: "", // 仓库名称
        depotNo: "", // 仓库编码
        depotId: "", // 仓库Id
        position: "", // 仓位
        //depotLocation: "", // 库位
        inventoryId: "", // 存货Id
        inventoryNo: "", // 存货编码
        inventoryName: "", //  存货名称
        standardModel: "", // , 规格型号
        unit: "", // 单位
        number: "", // 	数量
        money: "", // 金额
        sendReceiveType: "", // 收发类别
        sendReceiveTypeId: "", // 收发类别Id
        batchNo: "", // 批次号
        transferDate: "", // 转库日期
        remark: "", // 备注
        packageInventoryInformationList: [], // 配件列表
        partsInventoryInformationList: [], // 成套件列表
        positionList: [],
        BatchList: [], // 批次号列表
      });
    },
    // 根据源单生成物品初始化
    setGoodsInit(key) {
      this.DataSource = [];
      for (let i = 0; i < key; i++) {
        let data = {
          key: i + 1,
          isNew: true,
          assembleType: "", //     组装类型
          depotName: "", // 仓库名称
          depotNo: "", // 仓库编码
          depotId: "", // 仓库Id
          position: "", // 仓位
          //depotLocation: "", // 库位
          inventoryId: "", // 存货Id
          inventoryNo: "", // 存货编码
          inventoryName: "", //  存货名称
          standardModel: "", // , 规格型号
          unit: "", // 单位
          number: "", // 	数量
          money: "", // 金额
          sendReceiveType: "", // 收发类别
          sendReceiveTypeId: "", // 收发类别Id
          batchNo: "", // 批次号
          transferDate: moment().format("YYYY-MM-DD"), // 转库日期
          remark: "", // 备注
          packageInventoryInformationList: [], // 配件列表
          partsInventoryInformationList: [], // 成套件列表
          positionList: [], //
          BatchList: [], // 批次号列表
        };
        this.DataSource.push(data);
      }
    },

    // 设置
    setGoodsListInfo(data) {
      console.log("数据为:::::", data);

      this.setGoodsInit(data.length * 2);
      let sum = 0;
      for (let i = 0; i < data.length; i++) {
        // 成套件
        this.DataSource[i * 2].assembleType = 2;
        this.DataSource[i * 2].depotId = data[i].partsdepotId;
        this.DataSource[i * 2].depotNo = data[i].partsdepotcode;
        this.DataSource[i * 2].depotName = data[i].partsdepotName;
        this.DataSource[i * 2].inventoryId = data[i].partsInventoryId;
        this.DataSource[i * 2].inventoryNo = data[i].partsInventoryNo;
        this.DataSource[i * 2].inventoryName = data[i].partsInventoryName;
        this.DataSource[i * 2].standardModel =
          data[i].partsInventoryStandardModel;
        this.DataSource[i * 2].unit = data[i].partsInventoryUnit;
        this.DataSource[i * 2].number = data[i].partsInventoryNumber;

        // 配件
        this.DataSource[i * 2 + 1].assembleType = 1;
        this.DataSource[i * 2 + 1].depotId = data[i].packagedepotId;
        this.DataSource[i * 2 + 1].depotNo = data[i].packagedepotcode;
        this.DataSource[i * 2 + 1].depotName = data[i].packagedepotName;
        this.DataSource[i * 2 + 1].inventoryId = data[i].packageInventoryId;
        this.DataSource[i * 2 + 1].inventoryNo = data[i].packageInventoryNo;
        this.DataSource[i * 2 + 1].inventoryName = data[i].packageInventoryName;
        this.DataSource[i * 2 + 1].standardModel =
          data[i].packageInventoryStandardModel;
        this.DataSource[i * 2 + 1].unit = data[i].packageInventoryUnit;
        this.DataSource[i * 2 + 1].number = data[i].packageInventoryNumber;

        console.log(data[i].processTotalMoney);
        sum = sum + Number(data[i].processTotalMoney);
        // this.DataSource[i+1]. =
      }

      this.Form.assemblyTotalCost = sum;
    },

    // 重置所有信息
    ResetAll() {
      this.Form = {
        document: "", // 单据号
        document_date: moment().format("YYYY-MM-DD"), // 单据日期
        assemblyTotalCost: "", // 组装费用
        supplier: "", // 供应商 -- 挂账单位
        supplierId: "", // 供应商Id

        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        singleProducer: this.$store.state.user.info.username, // 制单人
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
        remarks: "", // 备注
      };
      this.DataSource = [];
      this.getApplyOrder();
      this.setDataSource();
    },

    // 组装新增物品和表单信息
    saveAssemblyOrderAndGoods() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 保存组装新增物品和表单信息
          let addArray = [];
          // 表格信息
          for (let i = 0; i < this.DataSource.length; i++) {
            if (this.DataSource[i].inventoryId != "") {
              let data = {
                type: this.DataSource[i].assembleType, // 	组装类型id(外键)
                depotId: this.DataSource[i].depotId, // 	仓库id(外键)
                position: this.DataSource[i].position, // 仓位
                //depotLocation: this.DataSource[i].depotLocation, // 库位
                inventoryId: this.DataSource[i].inventoryId, // 	存货编码(外键)
                number: this.DataSource[i].number, // 	数量
                sendAndReceiveCategory: this.DataSource[i].sendReceiveTypeId,
                //	收发类别
                batchNo: this.DataSource[i].batchNo, // 批次号
                transferDate: this.DataSource[i].transferDate, // 	转库日期
                remark: this.DataSource[i].remark, // 	备注
              };
              addArray.push(data);
            }
          }
          // 表單信息
          let data = {
            auditMark: 2, // 	审核标志
            bookkeepingMark: 2, // 记账标志
            document: this.Form.document, // 单据号
            documentTime: this.Form.document_date, // 单据日期

            assemblyCost: this.Form.assemblyTotalCost, // 组装费用
            farmer: this.Form.supplierId, // 农户Id // 挂账单位
            pkCalbody: this.Form.pkCalbody,
            pkCorp: this.Form.corpId,
            remark: this.Form.remarks, // 	备注
            // 负责人
            preparedBy: this.Form.singleProducerId, // 	制单人
            reviewer: this.Form.inspectorId, // 审核人
            warehouseAssemblyFormEntity: addArray,
          };
          console.log("提交的数据为:::::", data);

          // this.checkempty(data); //校验
          // if (this.empty_) {
          bhtzjHttp.saveAssemblyOrderAndGoods(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("提交成功");
              this.ResetAll();
            } else {
              this.$message.error("提交失败");
            }
          });
          // }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //校验是否为空
    checkempty(option) {
      this.empty_ = true;
      var message = []; //提示信息
      if (option.document == "") {
        message.push("系统错误，请从新刷新页面！！！！！！");
        this.empty_ = false;
      }
      if (option.documentTime == "") {
        message.push("单据日期不能为空!" + "\xa0\xa0\xa0");
        this.empty_ = false;
      }
      if (option.assemblyCost == "") {
        message.push("组装费用不能为空!" + "\xa0\xa0\xa0");
        this.empty_ = false;
      }
      if (option.farmer == "") {
        message.push("供应商不能为空!" + "\xa0\xa0\xa0");
        this.empty_ = false;
      }
      if (option.reviewer == "") {
        message.push("审核人不能为空!" + "\xa0\xa0\xa0");
        this.empty_ = false;
      }

      if (!this.empty_) {
        this.$message.error(message);
      }
    },

    // 组装更新物品和表单信息
    updateAssemblyOrderAndGoods() {
      let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let updateArray = [];
      // 物品
      for (let i = 0; i < newData.length; i++) {
        if (newData[i].isNew == false) {
          let data = {
            id: this.DataSource[i].id, // Id
            // type: this.DataSource[i].assembleType, // 	组装类型id(外键)
            // depotId: this.DataSource[i].depotId, // 	仓库id(外键)
            // inventoryId: this.DataSource[i].inventoryId, // 	存货信息id(外键)
            // number: this.DataSource[i].number, // 	数量
            // money: this.DataSource[i].money, // 	金额
            sendAndReceiveCategory: parseInt(
              this.DataSource[i].sendReceiveTypeId
            ), //	收发类别
            batchNo: this.DataSource[i].batchNo, // 批次号
            transferDate: this.DataSource[i].transferDate, // 	转库日期
            remark: this.DataSource[i].remark, // 	备注
          };
          updateArray.push(data);
        }
      }
      // 单据  要修改的地方
      let data = {
        id: this.Form.id,
        document: this.Form.document, // 单据号
        documentTime: this.Form.document_date, // 单据日期
        assemblyCost: this.Form.assemblyTotalCost, // 组装费用

        farmer: this.Form.supplierId, // 农户Id // 挂账单位

        remark: this.Form.remarks, // 	备注

        pkCorp: this.Form.corpId, // 公司
        pkCalbody: this.Form.pkCalbody, // 库存组织

        // preparedBy: this.Form.singleProducerId, // 	制单人
        reviewer: this.Form.inspectorId, // 审核人
        warehouseAssemblyFormEntity: updateArray,
      };
      console.log("要更新的数据::::::", data);
      bhtzjHttp.updataAssemblyOrderAndGoods(data).then((res) => {
        console.log(res);
      });
    },

    // 新增组装物品
    saveAssemblyGoods() {
      let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let addArray = [];
      for (let i = 0; i < newData.length; i++) {
        if (newData[i].isNew == true) {
          let data = {
            headId: this.otherId, // 表一Id
            type: newData[i].assembleType, // 组装类型
            depotId: newData[i].depotId, // 	仓库id  // 仓库编码
            position: newData[i].position, // 仓位
            //depotLocation: newData[i].depotLocation, // 库位
            inventoryId: newData[i].inventoryId, // 存货Id // 存货编码
            number: newData[i].number, // 数量
            money: newData[i].money, //  金额
            sendAndReceiveCategory: newData[i].sendReceiveTypeId, // 收发类别
            batchNo: newData[i].batchNo, // 批次号
            transferDate: newData[i].transferDate, // 转库日期
            remark: newData[i].remark, // 备注
          };
          addArray.push(data);
        }
      }
      bhtzjHttp.saveAssemblyGoods(addArray).then((res) => {
        if (res.code == 200) {
          this.$message.success("提交成功");
        } else {
          this.$message.error("提交失败");
        }
      });
    },

    // 删除组装物品
    deleteAssemblyGoods(id) {
      bhtzjHttp.deleteAssemblyOrderAndGoods("?id=" + id).then((res) => {
        if (res.code == 200) {
          this.$message.success("删除成功");
        } else {
          this.$message.error("删除失败");
        }
      });
    },

    // 保存
    Save() {
      // 通过更新标志来控制，是否是路由跳转过来的，还是新打开的页面
      // 如果是路由跳转过来的，那就是在原有的基础上进行修改，走修改接口和新增接口，修改物品和新增订单物品
      // 如果不是路由跳转过来的，走新增两个接口，新增订单和新增订单物品
      if (this.UpdateTmp) {
        console.log("这是更新");
        this.updateAssemblyOrderAndGoods();
        // this.addAssemblyGoods();
      } else {
        console.log("这是新增");
        this.saveAssemblyOrderAndGoods();
      }
    },

    // -------------------- 已经写完的 ::::::::::: --------------------------

    // 表格取消一行
    cancle(key) {
      // console.log(key);
      if (this.DataSource.length > 1) {
        this.DataSource.splice(key - 1, 1);
        // 对序号进行重新赋值
        for (let i = key - 1; i < this.DataSource.length; i++) {
          this.DataSource[i].key = i + 1;
        }
        this.$message.success("取消成功");
      } else {
        this.$message.error("至少保留一行");
      }
    },

    // 表格选择事件,
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },

    // 獲取倉庫Id
    getDepotId(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.depotNo.split("|");
      target.depotNo = array[0]; // 仓库id
      target.depotName = array[1]; // 仓库名称
      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.depotId = SotrageInfo.depotId;

      // 获取仓位列表
      // let positionList = await this.getPositionList(target.depotId);
      // let TempList = await this.disableParent(positionList);
      // console.log("仓位列表111", TempList);
      // target.positionList = TempList;
      // console.log(target);
    },

    // 获取存货信息
    async getInventoryInfo(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      // 分割字符串,取出来存货编码
      let array = target.inventoryNo.split("|");
      target.inventoryNo = array[0]; // 赋值给存货编码
      target.inventoryName = array[1]; // 赋值给存货名称

      if (target.assembleType == 2) {
        for (let i = 0; i < target.partsInventoryInformationList.length; i++) {
          if (array[0] == target.partsInventoryInformationList[i].inventoryNo) {
            target.inventoryId =
              target.partsInventoryInformationList[i].inventoryId;
            target.standardModel =
              target.partsInventoryInformationList[i].standardModel;
            target.unit = target.partsInventoryInformationList[i].unit;
            break;
          }
        }
      } else {
        for (
          let i = 0;
          i < target.packageInventoryInformationList.length;
          i++
        ) {
          if (
            array[0] == target.packageInventoryInformationList[i].inventoryNo
          ) {
            target.inventoryId =
              target.packageInventoryInformationList[i].inventoryId;
            target.standardModel =
              target.packageInventoryInformationList[i].standardModel;
            target.unit = target.packageInventoryInformationList[i].unit;
            break;
          }
        }
      }

      console.log("一条记录::::", target);

      target.BatchList = await this.getBatchNumberList(
        target.depotId,
        target.inventoryId
      ); // 获取批次列表

      console.log("筛选信息", target);
    },

    // 获取批次号
    getBatchNumberList(id1, id2) {
      let temp = [];
      return new Promise((resolve) => {
        comHttp
          .getgetBatchNumberById("?depotId=" + id1 + "&inventoryId=" + id2)
          .then((res) => {
            temp = res.result;
            resolve(temp);
          });
      });
    },

    //  ------------------------ 寫好的 ------------------------
    // 禁用父节点
    disableParent(Tree) {
      return new Promise((resolve) => {
        Tree.forEach((item) => {
          console.log(item);
          if (item.children.length != 0) {
            item[`disabled`] = true;
          } else {
            this.disableParent(item.children);
          }
        });
        resolve(Tree);
      });
    },

    // 获取仓位列表
    getPositionList(id) {
      let positionList = [];
      return new Promise((resolve) => {
        comHttp.getPositionInformationListByDepotId("?id=" + id).then((res) => {
          positionList = res.result[0].children;
          resolve(positionList);
        });
      });
    },
    // 获取组装字典表
    getAssemblyList() {
      comHttp.getAssemblyList().then((res) => {
        // console.log("组装类型::::", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: parseInt(res.result[i].value),
            title: res.result[i].title,
          };
          this.assembleTypeList.push(data);
        }
      });
    },

    // 获取组装单号
    getApplyOrder() {
      let queryPath = "?string=ZZDD-";
      comHttp.getOrder(queryPath).then((res) => {
        this.Form.document = res.message;
      });
    },

    // 获取收发类别列表
    // getSendReceiveList() {
    //   this.SendReceiveList = [];
    //   comHttp.getReceiveSendTypeListAll("").then((res) => {
    //     console.log("收发类别列表:::::", res);
    //     for (let i = 0; i < res.result.records.length; i++) {
    //       let data = {
    //         value: parseInt(res.result.records[i].id),
    //         title: res.result.records[i].name,
    //       };
    //       this.SendReceiveList.push(data);
    //     }
    //   });
    // },
    getSendReceiveList(queryPath = "") {
      console.log("hfougdiuy");
      comHttp.getReceiveSendTypeListAll(queryPath).then((res) => {
        console.log("收发类别列表", res);
        this.SendReceiveList = res.result;
      });
    },
    // 通过组装类型获取套件或者配件
    getGoodsInfoByAssembleType(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      console.log(target);
      if (target.assembleType == 1) {
        console.log("这是配件", this.getPackageInventoryInformationList());
        target.packageInventoryInformationList =
          this.getPackageInventoryInformationList();
      } else {
        console.log("这是成套件", this.getPartsInventoryInformationList());
        target.partsInventoryInformationList =
          this.getPartsInventoryInformationList();
      }
    },
    // 获取成套件信息列表
    getPartsInventoryInformationList() {
      let partsInventoryInformationList = [];
      comHttp.getAllPackageList().then((res) => {
        console.log("所有的成套件", res);
        for (let i = 0; i < res.result.list.length; i++) {
          let data = {
            inventoryId: res.result.list[i].partsInventoryInformationId, // 成套件Id
            inventoryNo: res.result.list[i].partsInventoryNo,
            inventoryName:
              res.result.list[i].partsInventoryInformationId_dictText, // 成套件名称
            standardModel: res.result.list[i].partsSpecificationsModel,
            unit: res.result.list[i].partsUnit, // 成套件名称
          };
          partsInventoryInformationList.push(data);
        }
      });
      return partsInventoryInformationList;
    },
    // 获取配件
    getPackageInventoryInformationList() {
      let packageInventoryInformationList = [];
      comHttp.getAllPackageList().then((res) => {
        console.log("所有的配件", res);
        for (let i = 0; i < res.result.list.length; i++) {
          let data = {
            inventoryId: res.result.list[i].packageInventoryInformationId, // 配件Id
            inventoryName:
              res.result.list[i].packageInventoryInformationId_dictText, // 配件名稱
            inventoryNo: res.result.list[i].inventoryNo,
            standardModel: res.result.list[i].specificationsModel,
            unit: res.result.list[i].unit, // 成套件名称
          };
          packageInventoryInformationList.push(data);
        }
      });
      return packageInventoryInformationList;
    },

    // 设置审核人id
    setInspector(value, options) {
      let array = value.split("|");
      this.Form.inspector = array[1];
      this.Form.inspectorId = options.key;
    },
    // 获取审核人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.inspectorList.push(data);
          this.inspectorIdList.push(res.result[i].userId);
        }
        if (this.inspectorIdList.indexOf(this.$store.state.user.info.id) > -1) {
          // 按钮状态改变:::::
          console.log(this.ExamineDisplay);
          this.ExamineDisplay = false;
        } else {
          this.ExamineDisplay = true;
        }
      });
    },

    // 获取负责人列表
    getResponsiblePersonList() {
      const roleName = "仓库负责人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.responsiblePersonList.push(data);
        }
      });
    },
    // 设置负责人id
    setResponsible_person(value, options) {
      let array = value.split("|");
      this.Form.responsiblePerson = array[1];
      this.Form.responsiblePersonId = options.key;
    },

    // 获取辅助单位
    getAuxiliary_Unitlist() {
      comHttp.getAuxiliaryUnit().then((res) => {
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            title: res.result[i].title,
            value: res.result[i].value,
          };
          this.Auxiliary_Unitlist.push(data);
        }
        // console.log("获取辅助单位列表::::",  this.Auxiliary_Unitlist);
      });
    },

    // 格式化出库日期
    getTransferDate(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      target.transferDate = moment(target.transferDate).format("YYYY-MM-DD");
      console.log("修改好的时间为::::", target.transferDate);
    },
    // 获取仓库
    getApplyStorage() {
      this.storageList = [];
      // 获取仓库名称
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },

    //获取收发类别Id
    getSendReceiveId(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.sendReceiveType.split("|");
      target.sendReceiveTypeId = parseInt(array[0]);
      target.sendReceiveType = array[1];
    },

    // 获取供应商Id
    getSupplierId(value, options) {
      this.Form.supplierId = options.key;
      console.log(this.Form.supplierId);
    },

    getCorpId(value) {
      let array = value.split("|");
      this.Form.corpId = array[0];
      console.log("数据为", this.Form);
    },
    // 删除
    Delete(id) {
      bhtzjHttp.deleteAssemblyGoods("?id=" + id).then((res) => {
        if (res && res.code === 200) {
          this.$message.success("删除成功");
        } else {
          this.$message.error("删除失败");
        }
      });
    },
  },
};
</script>

<style>
</style>